// read_sm2_cert.c
// 编译: gcc read_sm2_cert.c -o read_sm2_cert `pkg-config --cflags --libs hitls`
#include <stdio.h>
#include <hitls/x509.h>
#include <hitls/pem.h>
#include <hitls/bio.h>

int main(int argc, char **argv){
    if (argc != 2) {
        fprintf(stderr, "用法: %s sm2_cert.pem\n", argv[0]);
        return 1;
    }

    HITLS_Init();

    FILE *f = fopen(argv[1], "rb");
    if (!f) { perror("fopen"); return 1; }

    X509 *cert = PEM_read_X509(f, NULL, NULL, NULL);
    fclose(f);
    if (!cert) { fprintf(stderr, "读取失败\n"); return 1; }

    X509_NAME *sub = X509_get_subject_name(cert);
    char buf[256];
    X509_NAME_oneline(sub, buf, sizeof(buf));
    printf("Subject: %s\n", buf);

    X509_NAME *iss = X509_get_issuer_name(cert);
    X509_NAME_oneline(iss, buf, sizeof(buf));
    printf("Issuer: %s\n", buf);

    ASN1_TIME_print_fp(stdout, X509_get_notBefore(cert));
    printf(" - ");
    ASN1_TIME_print_fp(stdout, X509_get_notAfter(cert));
    printf("\n");

    EVP_PKEY *pub = X509_get_pubkey(cert);
    if (pub) {
        BIO *out = BIO_new_fp(stdout, BIO_NOCLOSE);
        printf("Public Key:\n");
        PEM_write_bio_PUBKEY(out, pub);
        BIO_free(out);
        EVP_PKEY_free(pub);
    }

    X509_free(cert);
    HITLS_Cleanup();
    return 0;
}
